import genService from "@/api/services/tool/genService";
import { LucideIcon } from "@/components/icon";
import IconButton from "@/components/icon/icon-button";
import Scrollbar from "@/components/scrollbar";
import { Button, Modal, Tabs, Tooltip, message } from "antd";
import { useEffect, useState } from "react";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { docco } from "react-syntax-highlighter/dist/cjs/styles/hljs";

import { useCopyToClipboard } from "@/hooks";

interface PreviewProps {
	visible: boolean;
	onCancel: () => void;
	tableName: string;
}

const CodePreview: React.FC<PreviewProps> = ({ visible, onCancel, tableName }) => {
	const [activeTab, setActiveTab] = useState<string>("");
	const [tabData, setTabData] = useState<Record<string, any>>({});
	const [loading, setLoading] = useState(false);

	const { copyFn } = useCopyToClipboard();

	// 获取tab数据
	const fetchTabData = async () => {
		if (!tableName) return;
		setLoading(true);
		try {
			const res = await genService.preview(tableName);
			if (res) {
				setTabData(res);
				// 设置第一个tab为激活状态
				const firstTab = Object.keys(res)[0];
				setActiveTab(firstTab);
			}
		} catch (error) {
			message.error("获取数据失败");
			console.error("获取tab数据失败:", error);
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		if (visible && tableName) {
			fetchTabData();
		}
	}, [visible, tableName]);

	const items = Object.entries(tabData).map(([key, value]) => ({
		key,
		label: key.substring(key.lastIndexOf("/") + 1, key.indexOf(".ftl")),
		children: (
			<Scrollbar>
				<SyntaxHighlighter language="java" style={docco} showLineNumbers>
					{value || ""}
				</SyntaxHighlighter>
				{/* 浮动按钮 */}
				<Tooltip placement="topLeft" title="复制">
					<IconButton
						style={{
							position: "absolute",
							top: "10px", // 调整按钮到面板的顶部
							right: "10px", // 调整按钮到面板的右侧
							backgroundColor: "#4CAF50",
							color: "white",
							border: "none",
							borderRadius: "5px",
							padding: "5px 10px",
							cursor: "pointer",
							zIndex: 10, // 确保按钮在面板之上
						}}
						onClick={() => copyFn(value)}
					>
						<LucideIcon name="Copy" size={20} />
					</IconButton>
				</Tooltip>
			</Scrollbar>
		),
	}));

	return (
		<Modal
			title="详细信息"
			open={visible}
			onCancel={onCancel}
			width="100%"
			style={{ top: 0, maxWidth: "98vw", padding: 10 }}
			styles={{
				body: { height: "calc(100vh - 200px)", overflow: "auto", padding: "10px 24px" },
				content: { maxWidth: "100vw", overflow: "hidden" },
				header: { padding: "16px 24px" },
				footer: { padding: "10px 24px" },
			}}
			footer={[
				<Button key="cancel" onClick={onCancel}>
					关闭
				</Button>,
			]}
		>
			<Tabs activeKey={activeTab} onChange={setActiveTab} items={items} loading={loading} />
		</Modal>
	);
};

export default CodePreview;
